package com.smartboard.network.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * Created by cheas on 2018/8/17.
 */
public class IdsPool {
    public static final int ID_TYPE_ROOM = 0;
    public static final int ID_TYPE_GAME = 1;
    public static final int ID_TYPE_USER = 2;

    //   31-30    29-27     26-0
    // [idtype][chesstype][idvalue]
    private static final int IDX_ID_TYPE = 30;
    private static final int IDX_CHESS_TYPE = 27;
    private static final int IDX_VALUE = 0;

    private static final int MAX_VALUE = (1<<(IDX_CHESS_TYPE-IDX_VALUE)) - 1;

    private static List<Integer> sIds = new ArrayList<>();
    private static Map<Integer, Object> sObjects = new HashMap<>();


    public static int createId(int idtype, int chessType) {
        Random random = new Random();
        int id = 0;
        do {
            id = random.nextInt(MAX_VALUE);
        } while(sIds.contains(id));

        return (idtype<<IDX_ID_TYPE) + (chessType<<IDX_CHESS_TYPE) + id;
    }

    public static void addObject(int id, Object obj) {
        sObjects.put(id, obj);
    }

    public static void removeObject(int id) {
        sObjects.remove(id);
    }

    public static Object getObject(int id) {
        return sObjects.get(id);
    }
}
